package com.example.demo.prototype;

import java.io.*;

public class CloneUtil {

    private CloneUtil() {
        throw new AssertionError();
    }

    @SuppressWarnings("unchecked")
    public static <T extends Serializable> T clone(T obj) throws Exception {
        ByteArrayOutputStream bout = new ByteArrayOutputStream();
        ObjectOutputStream oos = new ObjectOutputStream(bout);
        oos.writeObject(obj);
        ByteArrayInputStream bin = new ByteArrayInputStream(bout.toByteArray());
        ObjectInputStream ois = new ObjectInputStream(bin);
        return (T) ois.readObject();
        // 说明：调用 ByteArrayInputStream 或 ByteArrayOutputStream 对象的 close 方法没有任何意义
        // 这两个基于内存的流只要垃圾回收器清理对象就能够释放资源，这一点不同于对外部资源（如文件流）的释放
    }

    public static void main(String[] args) throws Exception{
        Person person = new Person("小王","20",new Car("宝马"));
        Person clone = clone(person);
        System.err.println(person);
        System.err.println(clone);
        System.out.println("============================");
        person.getCar().setName("奔驰");
        System.err.println(person);
        System.err.println(clone);
    }

}
